#include "pref_window.h"
#include "ui_pref_window.h"
#include <QMessageBox>
#include <QListWidget>
#include "timeobrowser.h"
#include <QDebug>
#include <QSettings>

/*
  TODO:
  _Design moche mais simple et efficace
  _demarage auto pour win cle de registre

  */

Pref_Window::Pref_Window(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Pref_Window)
{

    ui->setupUi(this);


    //SLOTS/SIGNAUX
    connect (ui->buttonBox,SIGNAL(accepted()),this,SLOT(Save_Config()));
    connect (ui->buttonBox,SIGNAL(rejected()),this,SLOT(hide()));
    connect (ui->btn_supprimer_codeTimeo,SIGNAL(clicked()),this,SLOT(Supprimer_Code_Timeo()));
    connect (ui->btn_ajouter_codeTimeo,SIGNAL(clicked()),this,SLOT(show_ChoixWeb()));


}

Pref_Window::~Pref_Window()
{
    delete ui;
}

void Pref_Window::showEvent(QShowEvent *event)
{
    //On recharche la configuration à chaque affichage
    ChargerConfig();
}



void Pref_Window::Supprimer_Code_Timeo()
{
    int reponse = QMessageBox::question(this,"Vous êtes sur ?","Voulez vous vraiment supprimer le code timéo"+ui->list_codeTimeo->currentRow(),QMessageBox::No|QMessageBox::Yes);

    if (reponse == QMessageBox::Yes )
    {
        qDebug()<<"delete"<<ui->list_codeTimeo->selectedItems().at(0)->text();
        delete ui->list_codeTimeo->selectedItems().at(0);
    }

}

void Pref_Window::show_ChoixWeb()
{
    //new instance fenetre de recup de code


    fenetre_get_code = new TimeoBrowser(this);
    fenetre_get_code->show();

    //Quand user valid on recupere le code
    connect (fenetre_get_code,SIGNAL(accepted()),this,SLOT(Ajouter_Code()));

}

void Pref_Window::Ajouter_Code()

{
    //qDebug() << "code_timeo_pref_window = " <<  fenetre_get_code->codeTimeo;
    ui->list_codeTimeo->addItem(fenetre_get_code->codeTimeo);
    delete fenetre_get_code;
}

void Pref_Window::Ajouter_Code(QString code_timeo)

{
    ui->list_codeTimeo->addItem(code_timeo);
}



void Pref_Window::Save_Config()
{
    //TODO:Surment une façon plus propre de save la liste des arrêts
    qDebug()<<"sauvegarde de la config";

QSettings save("TramNow","arrets",this);
QString id_arret;
qDebug()<<  ui->list_codeTimeo->count();
save.clear();
    for (int i = 0; i <= ui->list_codeTimeo->count() - 1 ;++i)
 {
        id_arret = "list_arret" + QString::number(i);
        qDebug() << id_arret << ui->list_codeTimeo->item(i)->text();
        save.setValue(id_arret,ui->list_codeTimeo->item(i)->text());
 }
    QMessageBox::information(this,"Information","Pour appliquer les changements, redemarer l'application",QMessageBox::Ok);
    close();

}

void Pref_Window::ChargerConfig()
{
    //TODO:Si changement de la façon de save list des arrêts
    //Il faut la corriger ici aussi.
    qDebug()<<"Lecture de la config";
    QSettings save("TramNow","arrets",this);
    QStringList cle =  save.allKeys();

    for (int i = 0 ; i <= cle.count() -1 ; i++)
    {
     Ajouter_Code(save.value(cle.at(i)).toString());
    }

}






